<script setup lang="ts">
import { createVNode, onMounted, ref } from 'vue';

import { Page, useVbenModal, z } from '@vben/common-ui';
import { AntDesignOutLined } from '@vben/icons';

import { message, Modal } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  sysParamsDelApi,
  sysParamsEditValApi,
  sysParamsQueryListApi,
} from '#/api/system/params';
import {
  sysParamsTypeAddApi,
  sysParamsTypeDelApi,
  sysParamsTypeEditApi,
  sysParamsTypeQueryListApi,
  sysParamsTypeRefreshCacheApi,
} from '#/api/system/paramsType';
import { queryDictOptionsApi } from '#/utils';
import { asyncValidDataApi } from '#/utils/handle/async-rules';
import ParamsFormModal from '#/views/system/params/modules/ParamsFormModal.vue';
import {
  handleFormVals,
  handleSchema,
} from '#/views/system/params/params.data';

const activeTab = ref();
const tabsList = ref();
const schemaList = ref([]);

const [FromModal, modalApi] = useVbenModal({
  connectedComponent: ParamsFormModal,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      loadParams();
    }
  },
});
const [TabModal, tabModalApi] = useVbenModal({
  title: 'Tab',
  confirmText: '提交',
  onCancel: () => {
    tabModalApi.close();
  },
  onConfirm: onSubmitTab,
});

const [TabsForm, tabsFormApi] = useVbenForm({
  layout: 'horizontal',
  wrapperClass: 'grid-cols-1 md:grid-cols-1 lg:grid-cols-1',
  showDefaultActions: false,
  commonConfig: {
    colon: true,
    labelWidth: 80,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      label: '名称',
      fieldName: 'belongKeyTitle',
      rules: 'required',
      componentProps: {
        placeholder: '请输入名称',
      },
    },
    {
      component: 'Input',
      label: 'key',
      fieldName: 'belongKey',
      help: '只能包含数字、字母且数字不能开头',
      componentProps: {
        placeholder: '请输入key',
      },
      dependencies: {
        rules(values, formApi) {
          const rowId = formApi.values?.id;
          return asyncValidDataApi(
            z
              .string({ required_error: '请输入key' })
              .min(3, 'key至少3个字符')
              .max(15, 'key最多30个字符')
              .regex(/^[a-z][a-z\d]*$/i, {
                message: '只能包含字母和数字，且不能以数字开头',
              }),
            {
              tableName: 'sys_params_type',
              fieldName: 'belong_key',
              rowId,
            },
          );
        },
        triggerFields: ['belongKey'],
      },
    },
    {
      component: 'InputNumber',
      label: '排序',
      fieldName: 'sortRank',
      componentProps: {
        placeholder: '请输入排序',
      },
    },
    {
      component: 'ApiRadioGroup',
      label: '状态',
      fieldName: 'status',
      defaultValue: 0,
      rules: 'required',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'status',
        },
      },
    },
  ],
});

const [ParamsForm, paramsFormApi] = useVbenForm({
  layout: 'horizontal',
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
  commonConfig: {
    colon: true,
    labelWidth: 100,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [],
  handleSubmit: onSubmit,
});

onMounted(async () => {
  await load();
});

/**
 * 加载数据
 */
async function load() {
  await loadTabs();
  await loadParams();
}

/**
 * 加载分类
 */
async function loadTabs() {
  tabsList.value = await sysParamsTypeQueryListApi({ status: 0 });
  activeTab.value = tabsList.value[0]?.id;
}
/**
 * 加载参数配置
 */
async function loadParams() {
  const paramsList = await sysParamsQueryListApi({
    typeId: activeTab.value,
  });
  schemaList.value = paramsList;
  const schema = await handleSchema(paramsList);
  const vals = await handleFormVals(paramsList);
  await paramsFormApi.setState(() => {
    return {
      schema,
    };
  });
  await paramsFormApi.setValues(vals, false);
}
// 点击切换Tab
async function handleChangeTabs() {
  await paramsFormApi.resetValidate();
  await loadParams();
}
const handleAddTabs = (targetKey: MouseEvent | string, action: string) => {
  if (action === 'add') {
    tabModalApi.open();
  } else {
    Modal.confirm({
      title: '系统提示?',
      content: createVNode('div', { style: 'color:red;' }, '确认删除所选吗?'),
      async onOk() {
        const msg = await sysParamsTypeDelApi(targetKey);
        message.success(msg);
        await loadTabs();
      },
      class: 'test',
    });
  }
};
// 编辑Tab项
async function handlerEditTab(row) {
  await tabModalApi.open();
  await tabsFormApi.setValues(row, false);
}
async function openForm(id) {
  modalApi.setData({
    id,
    typeId: activeTab.value,
  });
  modalApi.open();
}
async function onSubmitTab() {
  const { valid } = await tabsFormApi.validate();
  const values = await tabsFormApi.getValues();
  if (valid) {
    if (values?.id) {
      await sysParamsTypeEditApi(values);
      await tabModalApi.close();
      await loadTabs();
    } else {
      await sysParamsTypeAddApi(values);
      await tabModalApi.close();
      await loadTabs();
    }
  }
}
async function handleDel(row) {
  Modal.confirm({
    title: '系统提示?',
    content: createVNode('div', { style: 'color:red;' }, '确认删除所选吗?'),
    async onOk() {
      const msg = await sysParamsDelApi(row.id);
      message.success(msg);
      await loadParams();
    },
    class: 'test',
  });
}
async function onSubmit(values: Record<string, any>) {
  const msg = await sysParamsEditValApi(values);
  message.success(msg);
}
async function refreshCache() {
  const msg = await sysParamsTypeRefreshCacheApi();
  message.success(msg);
}
</script>

<template>
  <Page header-class="pb-0 pt-2" auto-content-height>
    <template #description>
      <a-tabs
        v-model:active-key="activeTab"
        type="editable-card"
        @edit="handleAddTabs"
        @change="handleChangeTabs"
        :tab-bar-style="{ marginBottom: 0 }"
      >
        <a-tab-pane
          v-for="item in tabsList"
          :key="item.id"
          :tab="item.belongKeyTitle"
        />
      </a-tabs>
    </template>
    <FromModal class="w-[50%]" />
    <TabModal class="w-[40%]">
      <TabsForm />
    </TabModal>
    <a-card class="h-full">
      <template #title>
        <a-button
          v-access:code="'sys:paramsItem:add'"
          class="mr-2"
          type="primary"
          @click="openForm()"
        >
          新增配置项
        </a-button>
        <a-dropdown>
          <a-button v-access:code="'sys:params:editTab'" type="primary">
            <span class="mr-1">Tab编辑</span>
            <AntDesignOutLined />
          </a-button>
          <template #overlay>
            <a-menu>
              <a-menu-item
                v-for="(item, index) in tabsList"
                :key="index"
                @click="handlerEditTab(item)"
              >
                {{ item.belongKeyTitle }}({{ item.belongKey }})
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
      <template #extra>
        <a-button class="mr-2" type="primary" @click="refreshCache">
          刷新缓存
        </a-button>
        <a-dropdown class="mr-2">
          <a-button v-access:code="'sys:paramsItem:edit'">
            <span class="mr-1">配置项编辑</span>
            <AntDesignOutLined />
          </a-button>
          <template #overlay>
            <a-menu>
              <a-menu-item
                v-for="(item, index) in schemaList"
                :key="index"
                @click="openForm(item.id)"
              >
                {{ item.configName }}({{ item.configField }})
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        <a-dropdown>
          <a-button v-access:code="'sys:paramsItem:del'">
            <span class="mr-1">配置项删除</span>
            <AntDesignOutLined />
          </a-button>
          <template #overlay>
            <a-menu>
              <a-menu-item
                v-for="(item, index) in schemaList"
                :key="index"
                @click="handleDel(item)"
              >
                {{ item.configName }}({{ item.configField }})
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
      <ParamsForm />
    </a-card>
  </Page>
</template>
